using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Microsoft.SharedSource.SqlServer.MDDE.Middleware;

namespace Microsoft.SharedSource.SqlServer.MDDE.ManagementStudio
{
    public partial class ImportPackage : Form
    {
        string repositoryConnectionString;
        string templatePath;

        public ImportPackage(string repositoryConnectionString)
        {
            InitializeComponent();

            this.repositoryConnectionString = repositoryConnectionString;

            //Kamal: Added code to fill the template combobox with the template names from the repository
            List<string> templates = MDDEManager.GetTemplateList(this.repositoryConnectionString);
            foreach(string template in templates)
            {
                this.cmbTemplate.Items.Add(template);
            }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            fd.Title = "Import Template";
            fd.Filter = "SSIS Packages|*.dtsx";
            fd.Multiselect = false;
            fd.ShowDialog();

            Cursor.Current = Cursors.WaitCursor;

            // TODO: Gray out all the controls here.

            this.Refresh();

            if (!string.IsNullOrEmpty(fd.FileName))
            {
                templatePath = fd.FileName;
                txtPackagePath.Text = templatePath;
            }

            // TODO: Reenable controls here.

            Cursor.Current = Cursors.Default;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            // TODO: Validate inputs.

            // Import the package.

            //Kamal: changed the code to pass the packae body insted of package name
            XmlDocument packageBody = new XmlDocument();
            packageBody.Load(txtPackagePath.Text);

            OperationResult result =
                MDDEManager.ImportPackage(
                repositoryConnectionString,
                cmbTemplate.Text,
                packageBody.InnerXml,
                txtPackageName.Text);

            //Kamal: added the code to close the window if package successfully 
            //imported and show a error message if not.
            if (result.SuccessStatus)
                this.Close();
            else
                MessageBox.Show(result.OperationLog[0], 
                    "Package import error", MessageBoxButtons.OK, 
                    MessageBoxIcon.Error);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}